﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Threading;

namespace TfsUtils.Ui.Mvvm.Ui
{
    public static class UiThread
    {
        public static void SetDispatcher(IDispatcher dispatcher)
        {
            Dispatcher = dispatcher;
        }

        private static IDispatcher Dispatcher;

        public static void Run(Action a)
        {
            if (DesignerProperties.GetIsInDesignMode(new DependencyObject()))
            {
                a();
            }
            else if (Dispatcher != null)
            {
                Dispatcher.Run(a);
            }
            else
            {
                throw new ArgumentNullException("", "Call UiThread.SetDispatcher() during the application initialization passing in a UiDispatcher or a NullDispatcher object");
            }
        }
    }

    /// <summary>
    /// used on the UI projects to let the UI binding works when the properties are
    /// changed by background threads.
    /// </summary>
    public class UiDispatcher : IDispatcher
    {
        public UiDispatcher(Dispatcher dispatcher)
        {
            Dispatcher = dispatcher;
        }

        public Dispatcher Dispatcher { get; private set; }

        public void Run(Action a)
        {
            Dispatcher.BeginInvoke(a);
        }
    }
}
